package com.jb.web.bean.list;

import com.jb.web.bean.FloatPanel;
import com.jb.web.bean.FormField;
import com.jb.web.bean.HtmlItem;
import com.jb.web.bean.Label;
import com.jb.web.bean.Link;
import com.jb.web.bean.ListBean;
import com.jb.web.bean.Page;
import com.jb.web.context.WebContext;
import com.jb.web.renderer.FloatPanelRenderer;

import java.util.Iterator;

import com.jb.faces.component.UIComponent;


public class PaginatorRenderer extends FloatPanelRenderer {
    public StringBuffer render(WebContext pCtx, UIComponent itemToRender) {
        resolve((FloatPanel)itemToRender);
        return super.render(pCtx, itemToRender);
    }

    private UIComponent getList(UIComponent hItem) {
        if (hItem == null) {
            return hItem;
        }
        if (hItem instanceof ListBean) {
            return hItem;
        }
        if (hItem instanceof Page) {
            return null;
        }
        return getList(hItem.getParent());
    }

    private void resolve(FloatPanel item) {
        Page page = item.getPage();
        HtmlItem hItem = (HtmlItem)page.getContained();
        ListBean lb = (ListBean)getList(hItem);
        if (lb == null)
            return;
        Iterator list = item.getChildren().iterator();
        while (list.hasNext()) {
            UIComponent child = (UIComponent)list.next();
            if (child instanceof Link)
                configLink(child, lb.getClientId());
            if (child instanceof Label) {
                String value = ((Label)child).getDefaultValue();
                if (value!=null && value.equals("total")) {
                    ((Label)child).setValue("" + lb.getPages());
                }
            }
            if (child instanceof FormField) {
                String value = ((FormField)child).getDefaultValue();
                if (value!=null && value.equals("page")) {
                    ((FormField)child).setValue("" + (1+lb.getCurrentPage()));
                }
            }
        }
    }

    private void configLink(UIComponent item, String listId) {
        Link hLink = (Link)item;
        String value = hLink.getDefaultValue();
        if ("next".equalsIgnoreCase(value)) {
            hLink.setOnClick("JBListBean.next('"+listId+"');");
        }
        if ("last".equalsIgnoreCase(value)) {
            hLink.setOnClick("JBListBean.last('"+listId+"');");
        }
        if ("previous".equalsIgnoreCase(value)) {
            hLink.setOnClick("JBListBean.previous('"+listId+"');");
        }
        if ("first".equalsIgnoreCase(value)) {
            hLink.setOnClick("JBListBean.first('"+listId+"');");
        }
    }
}
